
package com.hlkj.pay.app.merchant.ext.impl.huifu.handler.params;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import com.alibaba.fastjson.JSONObject;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.pay.app.merchant.ext.dto.access.ChannelMerchantAccessQueryContext;
import com.hlkj.pay.app.merchant.ext.dto.access.ChannelMerchantAccessSignContext;
import com.hlkj.pay.app.merchant.ext.impl.huifu.dto.access.HuiFuAccessQueryDto;
import com.hlkj.pay.app.merchant.ext.impl.huifu.dto.access.HuiFuSubAuthList;
import com.hlkj.pay.dto.merchant.MerchantAccessSignLink;
import com.hlkj.pay.enums.MerchantEnum;
import com.hlkj.pay.enums.PayEnums;
import com.hlkj.pay.infrastructure.model.merchant.MerchantAccessAuthDO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 汇付 商户进件参数处理
 * 
 * @author HlpayTeam
 * @date 2024/09/26 12:02
 */
@Slf4j
public class HuiFuMerchantResponseParamsHandle {

    /**
     * 查询返回参数处理
     * 
     * @param response
     * @param channelMerchantAccessQueryContext
     */
    public static void merchantAccessQueryParamsProcess(Map<String, Object> response, ChannelMerchantAccessQueryContext channelMerchantAccessQueryContext) {
        if (CollectionUtils.isEmpty(response)) {
            channelMerchantAccessQueryContext.setRemark("斗拱查询开户返回信息为空");
            channelMerchantAccessQueryContext.setProcessStatus(Boolean.FALSE);
            channelMerchantAccessQueryContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.APPROVE_REFUSE);
            return;
        }
        HuiFuAccessQueryDto huiFuAccessQueryDto = JsonUtils.parseObject(response.toString(), HuiFuAccessQueryDto.class);
        // String respCode = response.get("resp_code").toString();
        if (huiFuAccessQueryDto.isSuccess()) {
            // channelMerchantAccessQueryContext.setProcessStatus(CommonEnum.YES_NO_TYPE.YES);
            String applyStatus = huiFuAccessQueryDto.getApply_status();
            // Y：审核通过，P：审核中，N：审核拒绝，F：系统处理失败；
            switch (applyStatus) {
                case "Y":
                    channelMerchantAccessQueryContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.WAIT_SET);
                    break;
                case "P":
                    String agreementInfoList = huiFuAccessQueryDto.getAgreement_info_list();
                    if (StringUtils.hasText(agreementInfoList)) {
                        List<MerchantAccessSignLink> merchantAccessSignLinks = new ArrayList<>();
                        List<HuiFuAccessQueryDto.AgreementInfoListBean> agreementInfoListBeans = JsonUtils.parseArray(agreementInfoList,
                                HuiFuAccessQueryDto.AgreementInfoListBean.class);
                        agreementInfoListBeans.stream().forEach(agreementInfoListBean -> {
                            MerchantAccessSignLink merchantAccessSignLink = new MerchantAccessSignLink();
                            merchantAccessSignLink.setLink(agreementInfoListBean.getAgreement_link());
                            merchantAccessSignLink.setName(agreementInfoListBean.getAgreement_name());
                            merchantAccessSignLinks.add(merchantAccessSignLink);
                        });
                        channelMerchantAccessQueryContext.setSignLinks(merchantAccessSignLinks);
                        channelMerchantAccessQueryContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.CHANNEL_APPROVE);
                    }
                    channelMerchantAccessQueryContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.CHANNEL_APPROVE);
                    break;
                case "N":
                    if (huiFuAccessQueryDto.getApply_reason() != null) {
                        channelMerchantAccessQueryContext.setRemark(huiFuAccessQueryDto.getApply_reason());
                    }
                    else {
                        channelMerchantAccessQueryContext.setRemark("审批拒绝");
                    }
                    channelMerchantAccessQueryContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.APPROVE_REFUSE);
                    break;
                case "F":
                    if (huiFuAccessQueryDto.getApply_reason() != null) {
                        channelMerchantAccessQueryContext.setRemark(huiFuAccessQueryDto.getApply_reason());
                    }
                    else {
                        channelMerchantAccessQueryContext.setRemark("系统处理失败");
                    }
                    channelMerchantAccessQueryContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.APPROVE_REFUSE);
                    break;
                default:
                    channelMerchantAccessQueryContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.CHANNEL_APPROVE);
            }
            List<MerchantAccessAuthDO> merchantAccessAuthList = new ArrayList<>();
            if (StringUtils.hasText(huiFuAccessQueryDto.getAli_conf_result_list())) {
                List<HuiFuSubAuthList> huiFuSubAuthLists = JsonUtils.parseArray(huiFuAccessQueryDto.getAli_conf_result_list(), HuiFuSubAuthList.class);
                huiFuSubAuthLists.stream().forEach(huiFuSubAuthList -> {
                    MerchantAccessAuthDO merchantAccessAuthDO = new MerchantAccessAuthDO();
                    merchantAccessAuthDO.setType(PayEnums.PAY_TYPE.ALIPAY.getCode());
                    merchantAccessAuthDO.setStatus(HuiFuMerchantConfigParamsHandle.alipayStatus(huiFuSubAuthList.getReal_name_applyment_stat()).getCode());
                    merchantAccessAuthDO.setSubMchId(huiFuSubAuthList.getAli_bank_mer_code());
                    merchantAccessAuthDO.setSerialCode(huiFuSubAuthList.getPay_channel_id());
                    merchantAccessAuthDO.setAuthUrl(huiFuSubAuthList.getQrcode_data());
                    merchantAccessAuthDO.setRejectReason(huiFuSubAuthList.getReal_name_applyment_desc());
                    Map<String, String> channelJson = new HashMap<>();
                    channelJson.put("payScene", huiFuSubAuthList.getPay_scene());
                    merchantAccessAuthDO.setChannelJson(JsonUtils.toJsonString(channelJson));
                    merchantAccessAuthList.add(merchantAccessAuthDO);
                });
            }
            if (StringUtils.hasText(huiFuAccessQueryDto.getWx_conf_result_list())) {
                List<HuiFuSubAuthList> huiFuSubAuthLists = JsonUtils.parseArray(huiFuAccessQueryDto.getWx_conf_result_list(), HuiFuSubAuthList.class);
                Map<String, List<HuiFuSubAuthList>> collect = huiFuSubAuthLists.stream().collect(Collectors.groupingBy(huiFuSubAuthList -> huiFuSubAuthList.getWx_bank_mer_code()));
                collect.forEach((key,value)->{
                    HuiFuSubAuthList huiFuSubAuthList = value.get(0);
                    MerchantAccessAuthDO merchantAccessAuthDO = new MerchantAccessAuthDO();
                    merchantAccessAuthDO.setType(PayEnums.PAY_TYPE.WECHAT.getCode());
                    merchantAccessAuthDO.setStatus(HuiFuMerchantConfigParamsHandle.wechatStatus(huiFuSubAuthList.getReal_name_applyment_stat()).getCode());
                    merchantAccessAuthDO.setSubMchId(huiFuSubAuthList.getWx_bank_mer_code());
                    merchantAccessAuthDO.setSerialCode(huiFuSubAuthList.getPay_channel_id());
                    merchantAccessAuthDO.setRejectReason(huiFuSubAuthList.getReal_name_applyment_desc());
                    String qrcode_data = huiFuSubAuthList.getQrcode_data();
                    if (StringUtils.hasText(qrcode_data)) {
                        byte[] imageBytes = Base64.getDecoder().decode(qrcode_data);
                        merchantAccessAuthDO.setQrCodeArray(imageBytes);
                    }
                    Map<String, String> channelJson = new HashMap<>();
                    channelJson.put("payScene", huiFuSubAuthList.getPay_scene());
                    merchantAccessAuthDO.setChannelJson(JsonUtils.toJsonString(channelJson));
                    merchantAccessAuthList.add(merchantAccessAuthDO);
                });
            }
            if(!CollectionUtils.isEmpty(merchantAccessAuthList)){
                channelMerchantAccessQueryContext.setMerchantAccessAuthList(merchantAccessAuthList);
            }
        }
        else {
            String respDesc = huiFuAccessQueryDto.getResp_desc();
            channelMerchantAccessQueryContext.setProcessStatus(Boolean.FALSE);
            // channelMerchantAccessQueryContext.setAccessStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.APPROVE_REFUSE);
            if (StringUtils.hasText(respDesc)) {
                channelMerchantAccessQueryContext.setRemark(respDesc);
            }
            else {
                channelMerchantAccessQueryContext.setRemark("斗拱查询开户返回错误信息为空,错误码为:" + huiFuAccessQueryDto.getResp_code());
            }
        }
    }

    /**
     * 查询返回参数处理
     *
     * @param response
     * @param channelMerchantAccessQueryContext
     */
    public static void merchantAccessSignQueryParamsProcess(Map<String, Object> response, ChannelMerchantAccessSignContext channelMerchantAccessQueryContext) {
        if (CollectionUtils.isEmpty(response)) {
            channelMerchantAccessQueryContext.setRemark("斗拱查询开户返回信息为空");
            channelMerchantAccessQueryContext.setProcessStatus(Boolean.FALSE);
            channelMerchantAccessQueryContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.APPROVE_REFUSE);
            return;
        }
        HuiFuAccessQueryDto huiFuAccessQueryDto = JSONObject.parseObject(response.toString(), HuiFuAccessQueryDto.class);
        // String respCode = response.get("resp_code").toString();
        if (huiFuAccessQueryDto.isSuccess()) {
            // channelMerchantAccessQueryContext.setProcessStatus(CommonEnum.YES_NO_TYPE.YES);
            String applyStatus = huiFuAccessQueryDto.getApply_status();
            // Y：审核通过，P：审核中，N：审核拒绝，F：系统处理失败；
            switch (applyStatus) {
                case "N":
                    if (huiFuAccessQueryDto.getApply_reason() != null) {
                        channelMerchantAccessQueryContext.setRemark(huiFuAccessQueryDto.getApply_reason());
                    }
                    else {
                        channelMerchantAccessQueryContext.setRemark("审批拒绝");
                    }
                    channelMerchantAccessQueryContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.APPROVE_REFUSE);
                    break;
                case "F":
                    if (huiFuAccessQueryDto.getApply_reason() != null) {
                        channelMerchantAccessQueryContext.setRemark(huiFuAccessQueryDto.getApply_reason());
                    }
                    else {
                        channelMerchantAccessQueryContext.setRemark("系统处理失败");
                    }
                    channelMerchantAccessQueryContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.APPROVE_REFUSE);
                    break;
                case "Y":
                    channelMerchantAccessQueryContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.WAIT_SET);
                    break;
                default:
                    channelMerchantAccessQueryContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.WAIT_SIGNING);
            }
        }
        else {
            String respDesc = huiFuAccessQueryDto.getResp_desc();
            channelMerchantAccessQueryContext.setProcessStatus(Boolean.FALSE);
            // channelMerchantAccessQueryContext.setAccessStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.APPROVE_REFUSE);
            if (StringUtils.hasText(respDesc)) {
                channelMerchantAccessQueryContext.setRemark(respDesc);
            }
            else {
                channelMerchantAccessQueryContext.setRemark("斗拱查询开户返回错误信息为空,错误码为:" + huiFuAccessQueryDto.getResp_code());
            }
        }
    }

}
